#coding: utf-8
from django.db.models import Q
from django.shortcuts import render_to_response, get_object_or_404
from django.http import HttpResponseRedirect
from resources.forms import *
import string


def addResource( request, template_name ):
    if request.method == 'POST':
        form = AddResourceForm( request.POST )
        if form.is_valid():
            resource = form.save()
            return HttpResponseRedirect( '' )
    else:
        form = AddResourceForm()
    return render_to_response( template_name, { 'form': form } )

def searchResource( request, template_name):
    if request.method == 'POST':
        querykeys = '' + request.POST[ 'querykeys' ]
        keys = querykeys.split()
        query = None
        for key in keys:
            if ( query == None ):
                query = Q(title__contains = key) | Q(content__contains = key ) | Q( url__contains = key )
            else:
                query = query | Q(title__contains = key) | Q(content__contains = key ) | Q( url__contains = key )
        resources = Resource.objects.filter( query ).distinct()
        resources = list( resources )
    else:
        resources = []
    return render_to_response( template_name, { 'resources': resources } )

def showResource( request, resource_id, template_name ):
    resource = get_object_or_404( Resource.objects.select_related(), pk = resource_id )
    return render_to_response( template_name, { 'resources': resource, 'resource': resource })

def diggResource( request, resource_id, n, template_name ):
    resource =  Resource.objects.get( pk = resource_id )
    point = resource.digg + string.atoi(n)
    resource.digg = point
    resource.save()
    return render_to_response( template_name, { 'resources': resource, 'resource': resource })